import 'dart:async';
import 'package:flutter/material.dart';
import 'package:app_links/app_links.dart';
import 'package:ninetyfour/services/logger_service.dart';
import 'dart:io'; // 引入 dart:io 库
import 'package:url_launcher/url_launcher.dart';
import 'package:ninetyfour/manger/user_manger.dart';
import '../../l10n/app_localizations.dart';
import '../../manger/network_utils.dart';
import '../view/confirm_top_view.dart';
import '../../models/serach_info_model.dart';
import '../../manger/checkspu_utils.dart';
import '../view/confirm_info_view.dart';
import '../view/confirm_coupon_view.dart';
import '../../models/order_list_model.dart';
import '../view/confrim_payment_view.dart';
import '../view/confirm_price_view.dart';
import '../view/confirm_bottom_view.dart';
import '../view/confrim_czlist_view.dart';
import '../../models/account_ye_model.dart';
import '../../components/toast_utils.dart';
import '../../components/overlay_view.dart';
import '../../models/order_detail_model.dart';
import '../../manger/global_config.dart';
import '../../login/controller/webview.dart';
import '../../login/controller/webview_pay.dart';
import '../../models/adress_info_model.dart';
import '../../services/adress_manger.dart';
import '../view/confirm_adress_view.dart';
import '../../login/controller/adresss_pop_view.dart';
import '../view/qucik_pay_pop.dart';
import '../view/confirm_couponpop_view.dart';
import '../../manger/umevent_utils.dart';
import '../view/webView_maskview.dart';

class ConfirmPage extends StatefulWidget {
  final ReListModel selectedModel;
  final int pricenum;
  final String producttype;
  const ConfirmPage({Key? key, required this.selectedModel,required this.pricenum,required this.producttype}) : super(key: key);

  @override
  _ConfirmPageState createState() => _ConfirmPageState();
}

class _ConfirmPageState extends State<ConfirmPage> with WidgetsBindingObserver{
  final _scrollController = ScrollController();
  DateTime? _lastClickTime;
  ConfirmModel? txInfoModels;
  List<PayListModel>? payListModel;
  double balance = 0.0; // 账户余额
  double newBalance = 0.0; // 计算后账户余额
  double dis = 0.0; // 计算完价格
  double totalPrice = 0.0; //原最终金额
  double discount = 0.0; // 优惠卷折扣金额
  double shouxucount = 0.0; // 手续费金额
  String couponIds = ""; // 选中的优惠卷ID
  double priceFee = 0.0;
  PayListModel? shopPayment; // 支付方式ID
  int shopPaymentId = 0; // 支付方式ID
  bool isShowMemberIcon = false; // 是否显示充值信息右边图标
  bool isShowMemberList = false; // 是否显示充值信息列表
  bool isShowPopCoupon = false; // 是否显示弹窗优惠卷列表
  List<GroupListModel>? groupData; // 充值信息列表数据
  String orderId = ''; // 订单ID

  String areaText = ''; // info里面type为1时，需要选择地区
  String accountId = ''; // info里面type为0时，需要填写id
  final GlobalKey<ConfrimInfoViewState> confirmKey = GlobalKey<ConfrimInfoViewState>();
  bool isPushSafri = false; // 是否是推送过来的
  late final AppLinks _appLinks;
  List<CardInfo> cardList = []; // 快捷卡列表
  String cardId = ''; // 选中的卡ID
  int selectASddress = 0; // 选中的账单ID
  StreamSubscription? _sub;
  bool isShowAddress = false; // 是否显示地址信息
  bool isdy = false; // 是否显示地址信息
  List<AdressInfo> adressInfo = []; // 地址信息列表
  List<AdressInfo> adressInfo2 = []; // 需要显示的地址信息列表 0 卡支付 1本地支付的账单地址
  bool showAddressView = false;
  String urls = '';
  @override
  void initState() {
    super.initState();
    _fetchData();
    // _initDeepLinkListener();
    WidgetsBinding.instance.addObserver(this); // 监听生命周期
    initUniLinks();
    UmengEvent.trackEvent("orderconfirm_launch","进入确认订单页","");
  }

  void initUniLinks() async {
     _appLinks = AppLinks();

    try {
      // 冷启动处理（首次启动 app 时的 deep link）
      final Uri? initialUri = await _appLinks.getInitialLink();
      if (initialUri != null) {
        handleIncomingLink(initialUri.toString());
      }
    } catch (e) {
    }

    // 运行时监听（app 运行中收到 deep link）
    _sub = _appLinks.uriLinkStream.listen(
      (Uri uri) {
        handleIncomingLink(uri.toString());
      },
      onError: (err) {
      },
    );
  }

  void handleIncomingLink(String link) {
    final uri = Uri.parse(link);
    final token = uri.queryParameters["Apptokenc"];
    UserInfos.shared.productToken = token?? "";
  }

  Future<void> _fetchData() async {
    priceFee = double.tryParse(widget.selectedModel.priceFee) ?? 0.0;
    try {
      final response = await NetworkUtils.post(
        RequestCmd.checkout,
        body: {"itemId": widget.selectedModel.spuId, "num": widget.pricenum},
      );
      // LoggerService.logger.d(response);
      final model = ConfirmInfoModel.fromJson(response);
      if (model.code == 200) {
        if (model.data!.spuCheckout!.parameterList.isNotEmpty) {
          bool hasType4 = model.data!.spuCheckout!.parameterList.any((element) => element.type == 4);
          setState(() {
            balance = model.data!.spuCheckout!.balance;
            newBalance = model.data!.spuCheckout!.balance;
            txInfoModels = model.data!.spuCheckout;
            isdy = hasType4;
            payListModel = model.data!.paymentList;
            shopPayment = payListModel![shopPaymentId];
            if (shopPayment!.needAddress == 1) {
              showAddress();
            } else {
              isShowAddress = false;
            }
            if (model.data!.voList.isNotEmpty) {
              groupData = model.data!.voList;
              isShowMemberIcon = true;
            } else {
              isShowMemberIcon = false;
            }
          });
          _handlingFee(0);
        }
      }
    } catch (e) {
      print(e);
    }

    _payment();
  }

  Future<void> _payment() async {
    loadAddressData();
    payment();  
  }

  void loadAddressData() async {
    final manager = AdressInfoManager();
    final success2 = await manager.loadInfoData();
    if (success2.success) {
      adressInfo = success2.adressInfo ?? [];
      if (shopPayment!.localPayment == 0) {
        setState(() {
          adressInfo2 = adressInfo.where((item) => item.type == 0).toList();
        });
      } else {
        setState(() {
          adressInfo2 = adressInfo.where((item) => item.type == 1).toList();
        });
      }
    } 
  }

  void payment() async {
    final manager = AdressInfoManager();
    final success = await manager.loadCardList();
    if (success.success) {
      setState(() {
        cardList = success.cardInfo ?? [];
      });
    } 
  }

  Future<void> _handlingFee(int type) async {
    try {
      final response = await NetworkUtils.post(
        RequestCmd.cashier,
        body: {"itemId": widget.selectedModel.spuId, "num": widget.pricenum, "paymentMethod": type == 0 ? "" : shopPayment!.shopPaymentId},
      );
      final model = CashierModel.fromJson(response);
      if (model.code == 200) {
          final cashierData = model.data;
          setState(() {
            shouxucount = double.tryParse(cashierData?.processFee ?? '0.0') ?? 0.0;
            totalPrice = priceFee * widget.pricenum + shouxucount - discount;
            changePrice(totalPrice);
          });
          if (type == 0 && cashierData != null) {
            changePaylist(cashierData.paymentMethod);
          }
      }
    } catch (e) {
      print(e);
    }
  }

  void changePaylist(int paymentMethod) {
    if (paymentMethod > 1) {
      if (payListModel != null) {
        final index = payListModel!.indexWhere((item) => item.shopPaymentId == paymentMethod);
        if (index != -1) {
          setState(() {
            final item = payListModel!.removeAt(index);
            payListModel!.insert(0, item);
            shopPayment = item;
            if (item.needAddress == 1) {
              showAddress();
            } else {
              isShowAddress = false;
            }
          });
        }
      }
    }
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this); // 移除监听
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      // App 从后台回到前台（包括从浏览器返回）
      handleAppResume();
    }
  }

  void handleAppResume() {
    if (isPushSafri) {
      isPushSafri = false;
      OverlayView.shared.show(context, orderId);
    }
  }

  void createOrder() async {
    UmengEvent.trackEvent("orderconfirm_submit","确认订单页点击提交订单", shopPayment!.shopPaymentId.toString());

    final now = DateTime.now();
    if (_lastClickTime != null && now.difference(_lastClickTime!).inSeconds < 2) {
      return;
    }
    _lastClickTime = now;
    List<Map<String, dynamic>> values = confirmKey.currentState?.onGetAllValues() ?? [];
    if (values.isEmpty) {
      return;
    }
    if (dis > 0 ){
      if (shopPayment!.needAddress == 1) {
        if (adressInfo2.isEmpty) {
          ToastUtils.showCenterToast(context,  AppLocalizations.of(context)!.newcreateAddress);
          return;
        }
        cerateOrderForAddress(values);
      } else {
        if (shopPayment!.shopPaymentId == 22 || shopPayment!.shopPaymentId == 42) {
          UseePayment(values);
        } 
        else {
          ToastUtils.showLoadingToast(context);
          try {
            final response = await NetworkUtils.post(
              RequestCmd.create,
              body: {"spuId": widget.selectedModel.spuId, "num": widget.pricenum, "data": values,"couponsId":couponIds,"paymentMethod":shopPayment!.shopPaymentId},
            );
            ToastUtils.dismissLoadingToast();
            // print("createOrder response: $response");

            if (shopPayment!.shopPaymentId == 24 || shopPayment!.shopPaymentId == 25 || shopPayment!.shopPaymentId == 44 || shopPayment!.shopPaymentId == 45) {
              final model = OrderThreeModel.fromJson(response);
              if (model.code == 200) {
                UmengEvent.trackEvent("order_payment_success","创单成功",shopPayment!.shopPaymentId.toString());
                if (model.data?.orderId != null) {
                  orderId = model.data!.orderId;
                  pushWebView2(model.data!);
                } else {
                  print('orderId is null');
                }
              } else {
                UmengEvent.trackEvent("order_payment_failed","创单失败",model.msg);
                ToastUtils.showCenterToast(context, model.msg);
              }
            }else {
              final model = OrderModel.fromJson(response);
              if (model.code == 200) {
                UmengEvent.trackEvent("order_payment_success","创单成功",shopPayment!.shopPaymentId.toString());
                if (model.data?.orderId != null) {
                  orderId = model.data!.orderId;
                } 
                if (model.data?.redirectUrl != null) {
                  openLaunchUrl(model.data!.redirectUrl);
                } else {
                  OverlayView.shared.show(context,orderId);
                }
              } else {
                UmengEvent.trackEvent("order_payment_failed","创单失败",model.msg);
                ToastUtils.showCenterToast(context, model.msg);
              }
            }

          } catch (e) {
            ToastUtils.dismissLoadingToast();
            print(e);
          }
        }
      }

    } else {
      ToastUtils.showLoadingToast(context);
      try {
        final response = await NetworkUtils.post(
          RequestCmd.create,
          body: {"spuId": widget.selectedModel.spuId, "num": widget.pricenum, "data": values,"couponsId":couponIds},
        );
        ToastUtils.dismissLoadingToast();
        final model = OrderModel.fromJson(response);
        if (model.code == 200) {
          UmengEvent.trackEvent("order_payment_success","创单成功",shopPayment!.shopPaymentId.toString());
          if (model.data?.orderId != null) {
            orderId = model.data!.orderId;
            OverlayView.shared.show(context,orderId);
         
          } else {
            print('orderId is null');
          }
        } else {
          UmengEvent.trackEvent("order_payment_failed","创单失败",model.msg);
          ToastUtils.showCenterToast(context, model.msg);
        }
      } catch (e) {
        ToastUtils.dismissLoadingToast();
        ToastUtils.showCenterToast(context, "服务器出错了~");
        print(e);
      }
    }
  }

  void cerateOrderForAddress(List<Map<String, dynamic>> values) async {
    final adressId = adressInfo[selectASddress].id.toString();
    ToastUtils.showLoadingToast(context);
    try {
      final response = await NetworkUtils.post(
        RequestCmd.create,
        body: {"spuId": widget.selectedModel.spuId, "num": widget.pricenum, "data": values,"couponsId":couponIds,"paymentMethod":shopPayment!.shopPaymentId,"billingId":adressId},
      );
      // print(response);
      ToastUtils.dismissLoadingToast();
      final model = OrderThreeModel.fromJson(response);
      if (model.code == 200) {
        UmengEvent.trackEvent("order_payment_success","创单成功",shopPayment!.shopPaymentId.toString());
        if (model.data?.orderId != null) {
          orderId = model.data!.orderId;
          if (isShowAddress) {
            if ((model.data?.redirectUrl ?? '').isNotEmpty) {
              openLaunchUrl(model.data?.redirectUrl?? "");
            } else {
              pushWebView2(model.data!);
            }
          } else {
            showQuickPay(model.data!);
          }
        
        } 
      } else {
        UmengEvent.trackEvent("order_payment_failed","创单失败",model.msg);
        ToastUtils.showCenterToast(context, model.msg);
      }
    } catch (e) {
      UmengEvent.trackEvent("create_order_fail","创单失败",e.toString());
      ToastUtils.dismissLoadingToast();
      ToastUtils.showCenterToast(context, "服务器出错了~");
      print(e);
    }
  }

  void UseePayment(List<Map<String, dynamic>>values) async {
    Map<String, dynamic> useepayMsg = {
      "email": "",
      "firstName": "",
      "lastName": "",
    };
    ToastUtils.showLoadingToast(context);

    var param = {'spuId': widget.selectedModel.spuId,"num": widget.pricenum, "data": values,
      "paymentMethod": shopPayment!.shopPaymentId,"couponsId":couponIds,"useepayMsg":useepayMsg};

    final response = await NetworkUtils.get(
      RequestCmd.getUseePayData,
      params: param,
    );
    ToastUtils.dismissLoadingToast();
    final model = UseepayData.fromJson(response);
    if (model.code == 200) {
      pushWebView(param, model.data);
    } else {
      pushWebView(param);
    }

    ToastUtils.dismissLoadingToast();
  }

  void pushWebView(Map<String, dynamic> params, [UseepayModel? model]) {
    var price = widget.selectedModel.symbol + dis.toStringAsFixed(2);
    final url = UrlConfig.buildUrlString(price, model,context);

    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context2) => WebViewPage(
          title: AppLocalizations.of(context)!.cardpayment,
          url: url,
          oredrArrays: params,
          onOrderIdReceived: (receivedOrderId) {
            setState(() {
              orderId = receivedOrderId;
              if (orderId.isNotEmpty) {                
                OverlayView.shared.show(context,orderId);
              }
            });
          },
        ),
      ),
    );  
  }

  void pushWebView2(OrderInfoThreeModel model) {
    var finalUrlString = "";
    final String platformType = Platform.isIOS ? 'iOS' : 'Android';
    var price = widget.selectedModel.symbol + dis.toStringAsFixed(2);
    if (shopPayment!.shopPaymentId == 24 || shopPayment!.shopPaymentId == 44) {
      finalUrlString = "${UrlConfig.baseUrl}${UrlConfig.getTabsParam(context)}/appleAppPay?intent_id=${model.payInfo!.id}&client_secret=${model.payInfo!.clientSecret}&currency=${model.payInfo!.currency}&terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}&orderId=${model.orderId}&price=$price";
    } else if (shopPayment!.shopPaymentId == 25 || shopPayment!.shopPaymentId == 45) {
      finalUrlString = "${UrlConfig.baseUrl}${UrlConfig.getTabsParam(context)}/appGooglepay?intent_id=${model.payInfo!.id}&client_secret=${model.payInfo!.clientSecret}&currency=${model.payInfo!.currency}&terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}&orderId=${model.orderId}&price=$price";
      openLaunchUrl(finalUrlString);
      return;
    }
    else {
      final adressId = adressInfo[selectASddress].id.toString();
      finalUrlString = "${UrlConfig.baseUrl}${UrlConfig.getTabsParam(context)}/appAirwallex?intent_id=${model.payInfo!.id}&client_secret=${model.payInfo!.clientSecret}&currency=${model.payInfo!.currency}&terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}&orderId=${model.orderId}&price=$price&billingApp_id=$adressId";
    }
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context2) => WebViewPayPage(
          url: finalUrlString,
          onOrderIdReceived: (receivedOrderId) {
            OverlayView.shared.show(context,orderId);
          },
        ),
      ),
    ); 
  }

  void openLaunchUrl(String url) async{
    isPushSafri = true;
    await launchUrl(
      Uri.parse(url),
      mode: LaunchMode.externalApplication, // 👈 强制使用 Safari 打开
    );
  }

  void showQuickPay(OrderInfoThreeModel model) {
    var price = widget.selectedModel.symbol + dis.toStringAsFixed(2);
    // var msg = "应付金额：$price";
    var finalUrlString = "${UrlConfig.baseUrl}${UrlConfig.getTabsParam(context)}/appFastPay?intent_id=${model.payInfo!.id}&client_secret=${model.payInfo!.clientSecret}&paymentConsentId=$cardId&price=$price";
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => QuickPayAlertView(
        title: "${AppLocalizations.of(context)!.pleaseEnter}${AppLocalizations.of(context)!.securityCode}",
        url: finalUrlString,
        onClose: () {
          OverlayView.shared.show(context,orderId);
        },
      ),
    );

  }
  
  void changePrice(double price) {
    newBalance = price;
    dis = price;
    dis -= balance;
    if (dis <= 0) {
      setState(() {
        dis = 0;
        discount = discount;
      });
    } else {
      setState(() {
        newBalance = balance;
        discount = discount;
      });
    }
  }

  void clickQucikCardPay() {
    isShowAddress = false;
    for (var model in payListModel ?? []) {
      if (model.shopPaymentId == 23) {
        shopPayment!.shopPaymentId = 23;
      } else if (model.shopPaymentId == 28) {
        shopPayment!.shopPaymentId = 28;
      } else if (model.shopPaymentId == 43) {
        shopPayment!.shopPaymentId = 43;
      }
    }
    _handlingFee(1);
  }

  void changeAddress(int index) {
    selectASddress = index;
    final String platformType = Platform.isIOS ? 'iOS' : 'Android';
    final adressId = adressInfo[index].id.toString();
    String url = "${UrlConfig.baseUrl}/appBilling2?terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}&billingApp_id=$adressId&type=${shopPayment!.localPayment}";
    loadHtml(url);
  }

  void onAddAddress() {
    final String platformType = Platform.isIOS ? 'iOS' : 'Android';
    String url = "${UrlConfig.baseUrl}/appBilling2?terminal_app=$platformType&newstoken_app=${UserInfos.shared.token}&type=${shopPayment!.localPayment}";
    loadHtml(url);
  }

  loadHtml(String url) {
    setState(() {
      urls = url;
      showAddressView = true;
    });
  }

  hideAddressView() {
    setState(() {
      showAddressView = false;
    });
  }

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: Stack(
      children: [
        // 页面整体结构
        Column(
          children: [
            AppBar(
              toolbarHeight: 40,
              title: Text(
                AppLocalizations.of(context)!.confirmOrder,
                style: const TextStyle(fontSize: 17),
              ),
            ),
            Expanded(
              child: SingleChildScrollView(
                controller: _scrollController,
                child: Column(
                  children: [
                    ConfirmTopView(model: widget.selectedModel, pricenum: widget.pricenum, producttype: widget.producttype),
                    ConfrimInfoView(
                      key: confirmKey,  // 添加这行
                      txInfoModels: txInfoModels?.parameterList ?? [],
                      isShowMemberIcon: isShowMemberIcon,
                      accountId: accountId,
                      rechargeDetail: txInfoModels?.rechargeDetail ?? '',
                      rechargeDetailUrl: txInfoModels?.rechargeDetailUrl ?? '',
                      isDy: isdy,
                      areacode: areaText == '' ? '' : areaText,
                      onTap: () {
                        setState(() {
                          isShowMemberList = !isShowMemberList;
                        });
                      },
                      delegate: ConfrimInfoViewDelegate(
                        clickShowList: () {
                          // 处理显示列表逻辑
                          setState(() {
                            isShowMemberList = !isShowMemberList;
                          });
                        },
                        clickSureNext: () {
                          // 处理确认下一步逻辑
                          createOrder();
                        },
                        clickShowTTypeCode: (titles) {
                          showModalBottomSheet(
                            context: context,
                            builder: (context) {
                              return Container(
                                height: 200 + MediaQuery.of(context).padding.bottom,
                                child: Column(
                                  children: [
                                    Expanded(
                                      child: ListView.builder(
                                        itemCount: titles.length,
                                        itemBuilder: (context, index) {
                                          return ListTile(
                                            title: Center(child: Text(titles[index])),
                                            onTap: () {
                                              Navigator.pop(context);
                                              setState(() {
                                                areaText = titles[index];
                                              });
                                            },
                                          );
                                        },
                                      ),
                                    ),
                                  ],
                                ),
                              );
                            },
                          );
                        },
                      ),
                    ),
                    ConfirmCouponView(
                      selectedModel: widget.selectedModel,
                      pricenum: widget.pricenum,
                      couponIds:couponIds,
                      onShow: () {
                        setState(() {
                          isShowPopCoupon = !isShowPopCoupon;
                        });
                      },
                      onDiscountChanged: (p0, p1) {
                        setState(() {
                          discount = p0;
                          couponIds = p1;
                          totalPrice = priceFee * widget.pricenum + shouxucount - discount;
                          dis = totalPrice;
                          changePrice(dis);
                        });
                      },
                    ),
                    if (dis > 0)
                      PaymentView(
                        payList: payListModel ?? [],
                        cardList: cardList,
                        onShowAuthTips: () {
                           showDialog(
                            context: context,
                            builder: (BuildContext context) {
                              return Dialog(
                                backgroundColor: Colors.transparent,
                                child: WebViewMaskView(
                                  url: UrlConfig.fuinURL(context), // 这里放入你需要加载的 URL
                                  onDismiss: () {
                                    Navigator.pop(context); // 点击外部区域时退出 WebView
                                  },
                                ),
                              );
                            },
                          );
                        },
                        onCardSelected: (value) {
                          cardId = value;
                          clickQucikCardPay();
                        },
                        onSelected: (shop) {
                          setState(() {
                            shopPayment = shop;
                            shopPaymentId = shop.shopPaymentId;
              
                            if (shopPayment!.needAddress == 1) {
                              showAddress();
                            } else {
                              isShowAddress = false;
                            }
                            _handlingFee(1);
                          });
                        },
                      ),
                    if (isShowAddress)
                      ConfirmAddressView(
                        adressInfo: adressInfo2,   
                        onCLickAdd: () {
                          onAddAddress();
                        },
                        onChangeAddress: (value) {
                          changeAddress(value);
                        },                   
                      ),
                    ConfirmPriceView(
                      discount: discount,
                      balance: newBalance,
                      symbol: widget.selectedModel.symbol,
                      originalPrice: (double.tryParse(widget.selectedModel.priceFee) ?? 0.0) * widget.pricenum,
                      processFee: shouxucount,
                    ),
                  ],
                ),
              ),
            ),
            ConfirmBottomView(
              onConfirm: () {
                // 确认逻辑。创单
                createOrder();
              },
              totalPrice: dis.toStringAsFixed(2),
              symbol: widget.selectedModel.symbol,
            ),
          ],
        ),
        // 订单详情
        // 蒙层
        if (isShowMemberList)
          Positioned.fill(
            child: Container(
              color: Colors.black.withValues(alpha: 0.5),
              child: Center(
                child: CzzhListView(
                  groupData: groupData,
                  isShowIcon: (isShow) {
                    setState(() {
                      isShowMemberIcon = isShow;
                    });
                  },
                  onCellClick: (userID) {
                    setState(() {
                      accountId = userID;
                      isShowMemberList = false;
                    });
                    bool hasType0Field = txInfoModels!.parameterList.any((model) => model.type == 0);
                    if (!hasType0Field) {
                      // 假设confrimInfoKey是ConfrimInfoView的GlobalKey
                      confirmKey.currentState?.dyClickListId(userID);
                    }    
                  },
                  onClose: () {
                    setState(() {
                      isShowMemberList = false;
                    });
                  },
                ),
              ),
            ),
          ),
          if (isShowPopCoupon)
          Positioned.fill(
            child: Container(
              color: Colors.black.withValues(alpha: 0.5),
              child: Center(
                child: ConfrimYhMaskView(
                  selectedModel: widget.selectedModel,
                  priceNum: widget.pricenum,
                  couponIds:couponIds,
                  onClose: () {
                    setState(() {
                      isShowPopCoupon = false;
                    });
                  },
                  onSelectCoupon: (couponId) {
                    setState(() {
                      couponIds = couponId;
                      // isShowPopCoupon = false;
                    });
                  },
                ),
              ),
            ),
          ),
        if (urls != "")
        AddresssPopView(
          url: urls,
          visible: showAddressView,
          viewHeight: 550,
          onSaveSuccess: () {
            hideAddressView();
            loadAddressData(); // 刷新地址数据
          },
          onDismiss: hideAddressView,
        ),
      ],
    ),
  );
}

  void showAddress(){
    if (shopPayment!.localPayment == 0) {
      setState(() {
         adressInfo2 = adressInfo.where((item) => item.type == 0).toList();
      });
    } else {
      setState(() {
         adressInfo2 = adressInfo.where((item) => item.type == 1).toList();
      });
    }
    setState(() {
      isShowAddress = true;
      WidgetsBinding.instance.addPostFrameCallback((_) {
        if (_scrollController.hasClients) {
          _scrollController.animateTo(
            _scrollController.position.maxScrollExtent,
            duration: Duration(milliseconds: 300),
            curve: Curves.easeOut,
          );
        }
      });
    });
  }
}
